package favorites

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"savor_gin/controllers"
	. "savor_gin/errorType"
	"savor_gin/models"
	. "savor_gin/utils/token"
	"strconv"
	"time"
)

// 添加收藏

func AddFavor(c *gin.Context) {
	if contextData, exists := c.Get("contextData"); exists {
		if data, ok := contextData.(*TokenContext); ok {
			userId := data.Id
			var favor models.Favorites
			if err := c.ShouldBind(&favor); err != nil {
				controllers.SendResp(c, ParamBindError, nil)
				return
			}
			favor.CollectDate = time.Now()
			favor.UserID = userId
			if models.CheckFavor(favor.UserID, favor.RecipeID) {
				if err := favor.Create(); err != nil {
					controllers.SendResp(c, DataBaseError, err)
					return
				}
				controllers.SendResp(c, OK, nil)
				return
			} else {
				controllers.SendResp(c, IsFavoriteError, nil)
			}
		}
	} else {
		controllers.SendResp(c, TokenTimeOverError, nil)
		return
	}
}

// 删除收藏
func DeleteFavor(c *gin.Context) {
	if contextData, exists := c.Get("contextData"); exists {
		if data, ok := contextData.(*TokenContext); ok {
			userId := data.Id
			fmt.Println("delete:", userId)
			recipeId, err := strconv.Atoi(c.Param("recipeId"))
			fmt.Println("delete:", userId, recipeId)
			if err != nil {
				controllers.SendResp(c, ParamBindError, err)
				return
			}
			fmt.Println("delete:", userId, recipeId)
			if err := models.Delete(userId, uint64(recipeId)); err != nil {
				controllers.SendResp(c, DataBaseError, err)
				return
			}
			controllers.SendResp(c, OK, nil)
		}
	} else {
		controllers.SendResp(c, TokenTimeOverError, nil)
		return
	}
}

// 查询收藏列表
func GetFavorListByUserId(c *gin.Context) {
	userId, err := strconv.Atoi(c.Query("userId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	if s, err := models.GetFavor(uint64(userId)); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	} else {
		controllers.SendResp(c, OK, s)
	}
}

func CheckFavor(c *gin.Context) {
	if contextData, exists := c.Get("contextData"); exists {
		if data, ok := contextData.(*TokenContext); ok {
			userId := data.Id
			recipeId, err := strconv.Atoi(c.Query("recipeId"))
			if err != nil {
				controllers.SendResp(c, ParamBindError, err)
				return
			}
			if !models.CheckFavor(userId, uint64(recipeId)) {
				controllers.SendResp(c, Success, nil)
				return
			}
		}
	} else {
		controllers.SendResp(c, TokenTimeOverError, nil)
		return
	}
}

func CheckFavor1(c *gin.Context) {

}
